<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <el-button
            v-if="$permission('assetFinancialClassify:add')"
            :plain="true"
            :disabled="state.addBtn"
            @click="addClass"
            >{{ $t('btn_add') }}</el-button
          >
          <el-button
            v-if="$permission('assetFinancialClassify:delete')"
            :plain="true"
            :disabled="state.addBtn || state.categoryId === -1"
            @click="deleteClass"
            >删除</el-button
          >
          <el-button
            v-if="$permission('assetFinancialClassify:export')"
            :plain="true"
            @click="exportCategoryExcel()"
            >导出excel</el-button
          >
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="importProduct"
            :before-upload="beforeProductUpload"
            :action="uploadInfo.action"
          >
            <el-button v-if="$permission('assetFinancialClassify:import')"
              >导入</el-button
            >
          </el-upload>
          <el-button
            v-if="$permission('assetFinancialClassify:import')"
            :plain="true"
            @click="downloadTemplate('asset_financial_classify_import')"
            >下载导入模板</el-button
          >
        </div>
        <div class="left-container-header border-style-bottom">
          <el-input
            v-model="filterInfo.query.keyword"
            style="width: 200px; margin-left: 10px"
            :clearable="true"
            placeholder="请输入分类名称"
            @keyup.enter="init"
          ></el-input>
          <el-button :plain="true" @click="init">搜索</el-button>
        </div>
        <div class="left-container-main main-flex">
          <el-tree
            ref="menuTree"
            :data="treeInfo.data"
            highlight-current
            :props="treeInfo.defaultProps"
            node-key="id"
            :default-expanded-keys="treeInfo.treeData"
            :default-checked-keys="[treeInfo.checked]"
            :default-expand-all="false"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right-container" v-show="!state.saveBtn">
        <div class="layui-card-body">
          <div class="layui-btn-container border-style-bottom">
            <el-button
              v-if="$permission('assetFinancialClassify:update')"
              :plain="true"
              :disabled="state.saveBtn"
              @click="update"
              >{{ $t('btn_save') }}</el-button
            >
          </div>
          <div class="model-panel">
            <div class="model-panel-title">
              <p>基础信息</p>
            </div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formOrgInfo.ref"
              :data="formOrgInfo.data"
              :field-list="formOrgInfo.fieldList"
              :rules="formOrgInfo.rules"
              :label-width="formOrgInfo.labelWidth"
            >
            </page-form>
          </div>

          <div class="model-panel">
            <div class="model-panel-title">
              <p>折旧规则</p>
            </div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="depreciationInfo.ref"
              :data="depreciationInfo.data"
              :field-list="depreciationInfo.fieldList"
              :rules="depreciationInfo.rules"
              :label-width="depreciationInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="assetFinancialClassify">
import PageForm from '@/components/PageForm/index'
import {
  getCategoryTree,
  addCategory,
  updateCategory,
  deleteCategoryById,
  getCategoryDetailsById,
  exportCategory,
} from '@/api/asset'
import { ElMessage, ElLoading } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'

const { proxy } = getCurrentInstance()

const state = reactive({
  //控制左侧树节点上方新增按钮状态
  addBtn: true,
  saveBtn: true,
  addOrUpdate: '',
  RightBox: false,
  categoryId: '',
  isAddUpdate: 'add',
  flag: true,
})

// 过滤相关配置
const filterInfo = reactive({
  query: {
    keyword: '',
  },
})
const uploadInfo = reactive({
  action:
    axios.defaults.baseURL + '/asset/settings/financialClassify/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})

// 权限树
const treeInfo = reactive({
  data: [],
  nodeKey: 'code',
  treeData: [],
  checked: [],
  defaultProps: {
    children: 'children',
    label: function (data, node) {
      if (data.code) {
        return data.code + ' ' + data.name
      } else {
        return data.name
      }
    },
  },
})
const formOrgInfo = reactive({
  ref: null,
  data: {},
  labelWidth: '120px',
  fieldList: [
    {
      label: '分类名称',
      value: 'name',
      type: 'input',
      maxlength: 200,
      required: true,
    },
    {
      label: '分类编码',
      value: 'code',
      type: 'input',
      required: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
})
const depreciationInfo = reactive({
  ref: null,
  data: {
    residualRate: 0,
  },
  labelWidth: '120px',
  fieldList: [
    {
      label: '折旧方法',
      value: 'deprMethodType',
      type: 'select-model',
      clearable: false,
      checkDefault: true,
      code: 'depr_method_type',
    },
    {
      label: '折旧惯例',
      value: 'deprConvention',
      type: 'select-model',
      clearable: false,
      checkDefault: true,
      code: 'depr_convention',
    },
  ],
  rules: {
    code: [
      { required: true, message: '请输入分类编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    // deprConvention: [
    //   { required: true, message: "请选择折旧惯例", trigger: "blur" },
    // ],
    deprMethodType: [
      { required: true, message: '请选择折旧方法', trigger: 'blur' },
    ],

  },
})

watch(
  () => treeInfo.data,
  () => {
    state.RightBox = false
    state.addBtn = true
    state.saveBtn = true
  },
  {
    deep: true,
  }
)
watch(
  () => depreciationInfo.data.deprMethodType,
  (value) => {
    if (value == '0') {
      //如果不折旧，那么隐藏所有跟折旧有关的值，并置为0
      showFinanceFieldListItem(false, 'deprConvention')
      depreciationInfo.data['deprConvention'] = 0
    } else {
      showFinanceFieldListItem(true, 'deprConvention')
    }
  }
)

initRules()
onMounted(() => {
  init()
})

function init() {
  getCategoryTree(filterInfo.query).then((res) => {
    if (res && res.success) {
      let data = [res.data]
      formOrgInfo.data = {}
      depreciationInfo.data = {}
      treeInfo.data = data
      if (filterInfo.query.keyword) {
        treeInfo.treeData = []
        getNodeId(data, -1)
      } else {
        treeInfo.treeData = []
        getNodeId(data, 2)
      }
    }
  })
}
function getNodeId(data, num, count = 0) {
  count++
  data.forEach((item) => {
    if (count === num) {
      return
    }
    treeInfo.treeData.push(item.id)
    if (item.children && item.children.length) {
      getNodeId(item.children, num, count)
    }
  })
}
// 初始化校验规则
function initRules() {
  formOrgInfo.rules = proxy.$initRules(formOrgInfo.fieldList)
}
function showFinanceFieldListItem(show, nameValue) {
  let fieldList = depreciationInfo.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function addClass() {
  formOrgInfo.fieldList[1].disabled = false
  state.addOrUpdate = addCategory
  state.isAddUpdate = 'add'
  state.RightBox = false
  formOrgInfo.data = {}
  depreciationInfo.data = {}
  let parent = proxy.$refs.menuTree.getCurrentNode()
  state.saveBtn = false
  formOrgInfo.data = {
    parentId: parent.id,
  }
}
// 删除分类
function deleteClass() {
  proxy
    .$confirm('删除该分类会清空所有的子分类,确认删除该分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let id = state.categoryId //当前节点id
      deleteCategoryById(id).then((res) => {
        if (res.success) {
          init()
          state.isAddUpdate = 'add'
          formOrgInfo.data.name = ''
          formOrgInfo.data.code = ''
          formOrgInfo.data.remark = ''
        }
      })
    })
    .catch(() => {})
}
function getDetail() {
  getCategoryDetailsById(state.categoryId).then((res) => {
    formOrgInfo.data = {
      id: res.data.id,
      name: res.data.name,
      code: res.data.code,
      remark: res.data.remark,
      createTime: res.data.createTime,
      createUser: res.data.createUser,
      parentId: res.data.parentId,
      orgId: res.data.orgId,
      accrualMark: res.data.accrualMark,
    }
    formOrgInfo.fieldList[1].disabled = true
    depreciationInfo.data = {
      deprConvention: res.data.deprConvention,
      deprMethodType: res.data.deprMethodType,
    }
  })
}
// 点击树节点
function handleNodeClick(node) {
  formOrgInfo.ref.resetFields()
  depreciationInfo.ref.resetFields()
  state.isAddUpdate = 'update'
  state.addBtn = false
  state.addOrUpdate = updateCategory
  state.categoryId = node.id
  if (node.id !== -1) {
    state.saveBtn = false
    state.categoryId = node.id
    getDetail()
    state.RightBox = true
  } else {
    formOrgInfo.data = {}
    depreciationInfo.data = {}
    state.saveBtn = true
    state.RightBox = false
    formOrgInfo.fieldList[1].disabled = false
  }
}
async function update() {
  let flag = 0
  await formOrgInfo.ref.validate((valid) => {
    console.log(valid)
    if (valid) {
      console.log(valid, 'formOrgInfo.ref.validate')
      flag++
    }
  })
  await depreciationInfo.ref.validate((valid) => {
    console.log(valid)
    if (valid) {
      console.log(valid, 'depreciationInfo.ref.validate')
      flag++
    }
  })
  var returnedTarget = Object.assign(formOrgInfo.data, depreciationInfo.data)
  console.log(flag)
  if (flag == 2) {
    state.addOrUpdate(returnedTarget).then((res) => {
      if (res.success) {
        init()
      }
    })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      // tableInfo.value.selections = data;
      break
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3500,
      showClose: true,
      message: resp.msg,
    })
    init()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3500,
      showClose: true,
    })
  }
}
function exportCategoryExcel() {
  exportCategory(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function downloadTemplate(tag) {
  exportTemplateExcel(tag).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style lang="scss" scoped>
.left-container {
  min-width: 350px;
  .left-container-header {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
  }
  .border-style-bottom {
    margin-bottom: 0;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 120px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
  }
}
</style>
